package ch.jhc.sevlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.dbutils.QueryRunner;

import ch.jhc.bean.Article;
import ch.jhc.bean.User;
import ch.jhc.db.ArticleDao;
import ch.jhc.Global;

/**
 * Servlet implementation class ListArticleServlet
 */
@WebServlet("/admin/userlist.do")
public class ListUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String type = request.getParameter("type");
		if (type == null) {
			type = "html";
		}
		String pageParam = request.getParameter("page");
		int userCurrent = 1;
		
		try {
			if (pageParam != null) {
				userCurrent = Integer.valueOf(pageParam);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		long userTotal = 0L;
		QueryRunner runner = (QueryRunner)request.getServletContext().getAttribute(Global.KEY_QUERY_RUNNER);
		List<Article> userArticles = null;
		User user = (User) request.getSession().getAttribute(Global.CURRENT_USER);
		int creator = user.getId();
		try {
			userArticles = ArticleDao.userList(runner, userCurrent, creator);
			userTotal = ArticleDao.userTotal(runner, creator);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if (type.equals("html")) {
		//request + forward
		request.setAttribute("userArticles", userArticles);
		request.setAttribute("userCurrent", userCurrent);
		request.setAttribute("userTotal", userTotal/Global.PAGE_SIZE);
		request.setAttribute("userPage", userTotal/Global.PAGE_SIZE/8+1);
		request.getRequestDispatcher("wd.jsp").forward(request, response);//һ������
		}else if(type.equals("json")){
			response.setContentType("application/json; charset=utf8");
			JsonArrayBuilder builder = Json.createArrayBuilder();
			for (Article article : userArticles) {
				builder.add(article.toJson());
			}
			PrintWriter out = response.getWriter();
			out.print(builder.build().toString());
			
		}
		
	}


}
